package com.sfac.springboot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Description ParamFilter
 * @Author JiangHu
 * @Date 2022/8/22 10:31
 */
@WebFilter
public class ParamFilter implements Filter {
	public static final Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		LOGGER.debug("==== Init filter ====");
	}

	@Override
	public void doFilter(
			ServletRequest request,
			ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		LOGGER.debug("==== Do filter ====");

		// 将 ServletRequest 等转化为 HttpServletRequest 等
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resq = (HttpServletResponse) response;

		// 因为 HttpServletRequest 不能直接操作 parameterMap，所以构建 wrapper 对象来进行操作
		HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req) {

			// 重写 wrapper 对象的 getParameter 方法，替换掉脏字符串
			@Override
			public String getParameter(String name) {
				String value = super.getParameter(name);
				return StringUtils.isNotBlank(value) ?
						value.replaceAll("fuck", "***") : "";
			}

			@Override
			public String[] getParameterValues(String name) {
				String[] values = super.getParameterValues(name);
				if (values == null) {
					return new String[]{};
				}

				return Arrays.asList(values)
						.stream()
						.map(item -> item.replaceAll("fuck", "***"))
						.toArray(String[] :: new);
			}
		};

		// 将 wrapper 和 response 对象交出去
		chain.doFilter(wrapper, response);
	}

	@Override
	public void destroy() {
		LOGGER.debug("==== destroy filter ====");
	}
}
